<template>
  <van-nav-bar left-arrow title="搜索" @click-left="onClickLeft" />
  <div class="search-list">
    <van-search
      v-model="value"
      shape="round"
      background="#4fc08d"
      placeholder="请输入商品名称"
      @update:model-value="onChange"
    />

    <div class="home-goods">
      <!-- 循环渲染GoodsItem -->
      <template v-for="(item, key) in goodsList">
        <ListItem :goods="item" class="item" @click="open(item)" />
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import { getGoods } from '@/api/modules/goods'
import ListItem from './ListItem.vue'
const router = useRouter()
const value = ref('')
const goodsList = ref([])
// 搜索
const onChange = async (value) => {
  console.log(value)
  if (value !== '') {
    try {
      const {
        data: { data }
      } = await getGoods({ goodsName: value })
      console.log(data)
      if (data.list.length === 0) {
        goodsList.value = []
      } else {
        goodsList.value = data.list
      }
    } catch (error) {
      console.log(error)
    }
  } else {
    goodsList.value = []
  }
}

// 打开商品详情页
const open = (item) => {
  console.log(item)
  // 跳转到商品详情页
  router.push({
    name: 'GoodsDetail',
    query: {
      id: item.product_id
    }
  })
}

// 返回
const onClickLeft = () => history.back()
</script>

<style lang="less" scoped>
.search-list {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.home-goods {
  display: flex;
  flex-wrap: wrap;
  background-color: #f5f5f5;
  justify-content: space-around;
  padding: 10px;

  .item {
    // width: 45%;
    flex: 0 0 45%;
    margin-bottom: 10px;
    padding: 5px;
  }
  .item:last-child {
    margin-right: auto;
    margin-left: 9px;
  }
  // 最后一个item元素左对齐
}
</style>
